package com.xhsj.user.hr.system.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.xhsj.user.hr.process.processDefinition.query.MapQuery;
import com.xhsj.user.hr.system.entity.TbGlobalMenu;
import com.xhsj.user.hr.system.entity.TbGlobalRole;
import com.xhsj.user.hr.system.entity.UserRole;
import com.xhsj.user.hr.system.service.TbGlobalMenuService;
import com.xhsj.user.hr.system.vo.BatchAuthorizationVo;
import com.xhsj.user.hr.system.vo.GetRoleInfoByIdVo;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.*;
import java.util.stream.Collectors;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;


import com.xhsj.user.hr.system.service.TbGlobalRoleService;


/**
 * <p>
 * 角色信息表 前端控制器
 * </p>
 *
 * @author suxl
 * @since Aug 27, 2020 10:31:54 AM
 */
@Slf4j
@Api(tags = "角色信息表")
@RestController
@RequestMapping("/role/tbGlobalRole")
public class TbGlobalRoleController {

	@Autowired
    public TbGlobalRoleService service;

	@Autowired
	public TbGlobalMenuService tbGlobalMenuService;


	/**
	 * 保存/修改
	 * @author suxl
	 * @date Aug 27, 2020 10:31:54 AM
	 */
	@ApiOperation(value = "角色信息表,保存/修改", notes = "角色信息表,保存和修改方法")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('tb:sys:role:edit')")
	public Message save(@RequestBody TbGlobalRole data){
    	try {
			if (StringUtils.isNotBlank(data.getRoleId()) && data.getRoleId() == 1) {
				return Message.error("超级管理员不允许修改");
			}
    		service.saveRole(data);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("保存失败:{}",e);
        	return Message.error(1,e.getMessage());
		}

	}

	/*@ApiOperation(value = "角色信息表,保存/修改", notes = "角色信息表,保存和修改方法")
	@RequestMapping(value = "/testSaveRoleMenu", method = RequestMethod.GET)
	public void testSaveRoleMenu() {
		service.testSaveRoleMenu();
	}*/

	/**
	 * 通过id删除数据
	 * @author suxl
	 * @date Aug 27, 2020 10:31:54 AM
	 */
	@ApiOperation(value = "角色信息表删除", notes = "通过id删除角色信息表信息。")
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
    @PreAuthorize("hasAuthority('tb:sys:role:delete')")
	public Message delete(@RequestParam(value="id") Long id) {
		try {
			service.delRoleAndMenu(id);
        	return Message.success("成功");
		} catch (Exception e) {
			log.error("删除失败:{}",e);
            return Message.error(1,"失败");
		}
	}


	/**
	 * 查询用户RoleKeyNames列表
	 * @author 苏小林
	 * @date 2020/9/10 17:36
	 * @return: com.xhsj.user.utils.Message
	 */
	@ApiOperation(value = "查询用户RoleKeyNames列表", notes = "查询用户RoleKeyNames列表。")
	@RequestMapping(value = "/getUserRoleKeyNames", method = RequestMethod.GET)
	public Message getUserRoleKeyNames() {
		try {
			Long userId = UserUtils.getLoginAppUser().getUserId();
			List<String> list = service.getUserRoleKeyNames(userId);
			return Message.success("成功",list);
		} catch (Exception e) {
			log.error("失败:{}",e);
			return Message.error(1,"失败");
		}
	}


	@ApiOperation(value = "查询所有角色", notes = "查询所有角色。")
	@RequestMapping(value = "/findRoles", method = RequestMethod.GET)
	public Message findRoles() {
		try {
			List<MapQuery> list = service.findRoles();
			return Message.success("成功",list);
		} catch (Exception e) {
			log.error("删除失败:{}",e);
			return Message.error(1,"失败");
		}
	}

	/**
	 * 批量删除
	 * @author suxl
	 * @date Aug 27, 2020 10:31:54 AM
	 */
	@ApiOperation(value = "批量删除", notes = "批量删除。")
	@RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('tb:sys:role:delete')")
	public Message batchDelete(@RequestBody List<String> list) {
		try {
			service.removeByIds(list);
    		return Message.success("成功");
		} catch (Exception e) {
    		log.error("删除失败:{}",e);
    		return Message.error(1,"失败");
		}
    }

    /**
    * 分页查询数据
    * @author suxl
    * @date Aug 27, 2020 10:31:54 AM
    */
	@ApiOperation(value = "分页查询角色信息表list", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
	@RequestMapping(value="/findList",method = RequestMethod.POST)
    @PreAuthorize("hasAuthority('tb:sys:role:view')")
	public Message findList(@RequestBody Map<String,Object> data) {
        try {
        	IPage<TbGlobalRole> selectPage = service.selectPage(data);
    		return Message.success("成功",selectPage.getRecords(),selectPage.getTotal(),selectPage.getPages());
        } catch (Exception e) {
			log.error("查询异常:{}",e);
    		return Message.error(1,"失败");
        }
	}


	/**
	 * 查询所有角色列表
	 * @author 苏小林
	 * @date 2020/12/7 10:23
	 * @return: com.xhsj.user.utils.Message
	 */
	@RequestMapping(value="/findAllList",method = RequestMethod.GET)
	public Message findAllList() {
		try {
			List<TbGlobalRole> list = service.list();
			return Message.success("成功",list);
		} catch (Exception e) {
			log.error("查询异常:{}",e);
			return Message.error(1,"失败");
		}
	}

	/**
	 * 批量授权
	 * @author 苏小林
	 * @date 2020/12/7 10:53
	 * @return: com.xhsj.user.utils.Message
	 */
	@RequestMapping(value="/batchAuthorization",method = RequestMethod.POST)
	public Message batchAuthorization(@RequestBody BatchAuthorizationVo batchAuthorizationVo) {
		try {
			service.batchAuthorization(batchAuthorizationVo);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("查询异常:{}",e);
			return Message.error(1,"失败");
		}
	}


    /**
    * 通过id获取实体类
    * @author suxl
    * @date Aug 27, 2020 10:31:54 AM
    */
	@ApiOperation(value = "通过id获取角色信息表实体类", notes = "通过id获取角色信息表实体类。")
	@RequestMapping(value="/getRoleInfoById",method = RequestMethod.GET)
    // @PreAuthorize("hasAuthority('tb:sys:role:view')")
	public Message getRoleInfoById(@RequestParam(value="id") Long id) {
		GetRoleInfoByIdVo getRoleInfoByIdVo = new GetRoleInfoByIdVo();
		TbGlobalRole byId = service.getById(id);
		if (byId != null) {
			getRoleInfoByIdVo.setRoleId(byId.getRoleId());
			getRoleInfoByIdVo.setRoleName(byId.getRoleName());
			getRoleInfoByIdVo.setRoleKeyname(byId.getRoleKeyname());
			if (id == 1) { // 超级管理员
				QueryWrapper<TbGlobalMenu> menuWrapper = new QueryWrapper<>();
				menuWrapper.ne("id",1);// id 不为1
				List<TbGlobalMenu> list = tbGlobalMenuService.list(menuWrapper);
				List<Long> menuIds = list.parallelStream().map(TbGlobalMenu::getId).collect(Collectors.toList());
				getRoleInfoByIdVo.setMenuIds(menuIds);
			} else {
				Set<Long> roleIds = Sets.newHashSet(id);
				Set<TbGlobalMenu> list = tbGlobalMenuService.getAllMenuByRoleIds(roleIds);
				List<TbGlobalMenu> father = list.stream().filter(tbGlobalMenu -> tbGlobalMenu.getParentId() == 1).collect(Collectors.toList());
                List<TbGlobalMenu> menus = Lists.newArrayList(list);
                tbGlobalMenuService.setSubChild(father, menus);

                List<TbGlobalMenu> objects = Lists.newArrayList();
                tbGlobalMenuService.handleEchoMenu(menus,objects);
				List<Long> menuIds = objects.parallelStream().map(TbGlobalMenu::getId).collect(Collectors.toList());
				getRoleInfoByIdVo.setMenuIds(menuIds);
			}
		}
    	return Message.success("成功",getRoleInfoByIdVo);
	}

    /**
    * 通过id查询详细信息
    * @author suxl
    * @date Aug 27, 2020 10:31:54 AM
    */
	@ApiOperation(value = "通过id获取实体类详细信息", notes = "通过id获取实体类详细信息。")
	@RequestMapping(value="/detail",method = RequestMethod.GET)
    // @PreAuthorize("hasAuthority('tb:sys:role:view')")
	public Message detail(@RequestParam(value="id") String id) {
    	return Message.success("成功",service.getById(id));
	}


	/**
	 * 角色列表
	 * 入职时 预设角色
	 * @author liuqinghua
	 */
	@GetMapping("/loadList")
	public Message loadList() throws Exception {
		return Message.success("成功",service.loadList());
	}

	/**
	 * 获取唯一id，如果角色名称不存在
	 * @author 苏小林
	 * @date 2021/3/15 16:11
	 * @param: name
	 */
	@GetMapping("/getSnowIdIfNameNotExist")
	public Message getSnowIdIfNameNotExist(@RequestParam("name") String name) {

		try {
			if (StringUtils.isBlank(name)) {
				return Message.error("名称不能为空");
			}
            long snowId = service.getSnowIdIfNameNotExist(name);
            return Message.success("success",snowId);
		} catch (Exception e) {
			log.error("查询异常:{}",e);
			return Message.error(1,e.getMessage());
		}
	}



}

